import time

import kdj_utils
import numpy as np
import pandas as pd
import easyquotation
import easytrader

SLEEP_TIME_SECONDS = 3

XIADAN_CLIENT_PATH = r'D:\software\同花顺\xiadan.exe'
XIADAN_CLIENT = ''

# 股票数据列信息
STOCK_INFO_COLUMNS = ['CLOSE', 'HIGH', 'LOW']
STOCK_INFO_STORE = pd.DataFrame([[0, 0, 0]], columns=STOCK_INFO_COLUMNS)

STOCK_NO = '162411'
STOCK_BUY = 0  # 买入
STOCK_SELL = 1  # 卖出
STOCK_AMOUNT = 0


# 获取股票信息
def get_stock_info():
    print('get stock info.')
    quotation = easyquotation.use('sina')  # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
    # prefix 参数指定返回的行情字典中的股票代码 key 是否带 sz/sh 前缀
    quotation.market_snapshot(prefix=True)
    # 支持直接指定前缀，如 'sh000001'
    result = quotation.real(STOCK_NO)[STOCK_NO]

    a_stock_info = {
        STOCK_INFO_COLUMNS[0]: result['close'],
        STOCK_INFO_COLUMNS[1]: result['high'],
        STOCK_INFO_COLUMNS[2]: result['low'],
    }

    # print(a_stock_info)
    return a_stock_info


# 计算kdj数据
def calc_kdj():
    # j值为负买入, j值高于100卖出
    kdj_df = kdj_utils.get_kdj(STOCK_INFO_STORE)
    last_j_value = kdj_df['J'].iloc[-1]
    print(last_j_value)
    if last_j_value < 0:
        return STOCK_BUY
    else:
        return STOCK_SELL


def trader_init():
    user = easytrader.use('universal_client')
    user.enable_type_keys_for_editor()
    # 需要先打开软件,然后再使用
    user.connect(XIADAN_CLIENT_PATH)
    global XIADAN_CLIENT
    XIADAN_CLIENT = user


# 进行股票交易
def trade_buy():
    user = XIADAN_CLIENT
    price = get_stock_price()
    # user.buy(STOCK_NO, price=price, amount=STOCK_AMOUNT)
    print("buy")


# 进行股票交易
def trade_sell():
    user = XIADAN_CLIENT
    price = get_stock_price()
    # user.sell(STOCK_NO, price=price, amount=STOCK_AMOUNT)
    print("sell")


# 增加新股票交易数据
def insert_new_stock_info(info):
    global STOCK_INFO_STORE
    STOCK_INFO_STORE = STOCK_INFO_STORE.append(info, ignore_index=True)


# 获取股票信息
def get_stock_price():
    quotation = easyquotation.use('sina')
    quotation.market_snapshot(prefix=True)
    return quotation.real(STOCK_NO)[STOCK_NO]


# 主函数
if __name__ == '__main__':
 
    trader_init()

    while True:
        print("开始主程序")

        print("获取最新股票数据")
        stock_info = get_stock_info()

        print("更新股票信息数据库")
        insert_new_stock_info(
            pd.DataFrame([stock_info], columns=STOCK_INFO_COLUMNS)
        )

        print("计算KDJ")
        print("判断是否到达交易条件")
        stock_trade_type = calc_kdj()

        print("开始进行交易")
        if stock_trade_type == STOCK_BUY:
            print("进入买入")
            trade_buy()

        if stock_trade_type == STOCK_SELL:
            print("进行卖出")
            trade_sell()

        print("主程序退出")

        print("等待...")

        time.sleep(SLEEP_TIME_SECONDS)
        pass
